<template>
	<uni-popup ref="popup" :is-mask-click="false" type="bottom" style="z-index:999;">
		<view class="flex-col w-full" style="margin: 0 auto;">
			<view class="mb-12 flex justify-end">
				<image class="size-26" src="@/static/svg/icon-close.svg" @click.stop="onClose"></image>
			</view>
			<view class="radius-12 flex-col bg-white px-16 py-24">
				<view class="text-color-regular fs-14 font-semibold">订单导出</view>
				<view class="mt-20 text-color-regular fs-14">策划人</view>
				<view class="flex flex-wrap mt-20">
					<view
						v-for="(item, index) in businessList"
						:key="index"
						class="radius-8 h-44 inline-flex center fs-14 text-color-regular mr-12 mb-12 business-item p-12"
						:style="queryParam.businessIds.includes(item.businessId) ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="clickBusiness(item)"
					>{{ item.businessShortName }}</view>
				</view>
				<view class="mt-20 text-color-regular fs-14">时间</view>
				<view class="flex flex-wrap mt-20">
					<view
						class="radius-8 h-44 inline-flex center fs-14 text-color-regular mr-12 mb-12 item"
						:style="type === 1 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(1)"
					>近一个月</view>
					<view
						class="radius-8 h-44 inline-flex center fs-14 text-color-regular mr-12 mb-12 item"
						:style="type === 2 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(2)"
					>今日</view>
					<view
						class="radius-8 h-44 inline-flex center fs-14 text-color-regular mr-12 mb-12 item"
						:style="type === 3 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(3)"
					>昨日</view>
					<view
						class="radius-8 h-44 inline-flex center fs-14 text-color-regular mr-12 mb-12 item"
						:style="type === 4 ? 'background:#FFEEEE;border:1px solid #FA4543;color:#FA4543;': ''"
						@click="changeType(4)"
					>本周</view>
				</view>
				<view class="my-20 text-color-regular fs-14">自定义时间</view>
				<view class="flex item-center">
					<uni-datetime-picker
						type="datetime"
						:value="queryParam.startVerifyTime"
						@change="change($event, 'start')"
					>
						<view
							class="radius-8 h-44 w-full inline-flex center time-item"
							:style="queryParam.startVerifyTime ? 'color:#333333;' : ''"
						>
							{{ queryParam.startVerifyTime ? queryParam.startVerifyTime : '开始时间' }}
						</view>
					</uni-datetime-picker>
					<view class="w-8 h-1 bg-black mx-6"></view>
					<uni-datetime-picker
						type="datetime"
						:value="queryParam.endVerifyTime"
						@change="change($event, 'end')"
					>
						<view
							class="radius-8 h-44 w-full flex-1 inline-flex center time-item"
							:style="queryParam.endVerifyTime ? 'color:#333333;' : ''"
						>
							{{ queryParam.endVerifyTime ? queryParam.endVerifyTime : '结束时间' }}
						</view>
					</uni-datetime-picker>
				</view>
				<view class="mt-40">
					<button class="bg-primary radius-8 h-46 mx-16 text-white fs-16 font-semibold" @click="query">确定</button>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup name="ExportPopup">
	import dayjs from 'dayjs'
	import { ref, unref } from 'vue'
	import { exportApi } from '@/api/order.js'
	import { listMyBusiness } from '@/api/business.js'
	
	const popup = ref(null)
	const businessList = ref([])
	const type = ref() // 日期类型：1-近1个月，2-今日，3-昨日，4-本周
	const getBusinessList = () => {
		listMyBusiness().then((res) => {
			businessList.value = res
			if(res.length === 1){
				queryParam.value.businessIds.push(res[0].businessId)
			}
		})
	}
	
	const onClose = () => {
		popup.value && popup.value.close()
	}
	
	const showDialog = async (value) => {
		if (value) {
			popup.value && popup.value.open()
			getBusinessList()
		} else {
			onClose()
		}
	}
	
	const queryParam = ref({
		businessIds: [],
		startVerifyTime: '', // 核销开始时间,格式:yyyy-MM-dd HH:mm:ss
		endVerifyTime: '' // 核销结束时间,格式:yyyy-MM-dd HH:mm:ss
	})
	
	const clickBusiness = (item) => {
		let index = queryParam.value.businessIds.findIndex(businessId => businessId === item.businessId)
		if(index === -1){
			queryParam.value.businessIds.push(item.businessId)
		}else{
			queryParam.value.businessIds.splice(index, 1)
		}
	}
	
	const changeType = (val) => {
		switch(val) {
			case 1:
				queryParam.value.startVerifyTime = dayjs().subtract(30, 'day').format('YYYY-MM-DD HH:mm:ss')
				queryParam.value.endVerifyTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
			break;
			case 2:
				queryParam.value.startVerifyTime = dayjs().format('YYYY-MM-DD') + ' 00:00:00'
				queryParam.value.endVerifyTime = dayjs().format('YYYY-MM-DD') + ' 23:59:59'
			break;
			case 3:
				queryParam.value.startVerifyTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 00:00:00'
				queryParam.value.endVerifyTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD') + ' 23:59:59'
			break;
			case 4:
				queryParam.value.startVerifyTime = dayjs().day(1).format('YYYY-MM-DD') + ' 00:00:00';
				queryParam.value.endVerifyTime = dayjs().day(7).format('YYYY-MM-DD') + ' 23:59:59';
			break;
		}
		type.value = val
	}
	
	const change = (e, str) => {
		if (str === 'start') {
			if (queryParam.value.endVerifyTime) {
				const diffDay = dayjs(e).diff(queryParam.value.endVerifyTime, 'day')
				if (Math.abs(diffDay) > 90) {
					uni.showToast({
						icon: 'none',
						title: '时间跨度不能超过90天'
					})
					return
				}
			}
			queryParam.value.startVerifyTime = e
		} else if (str === 'end') {
			if (queryParam.value.startVerifyTime) {
				const diffDay = dayjs(e).diff(queryParam.value.startVerifyTime, 'day')
				if (Math.abs(diffDay) > 90) {
					uni.showToast({
						icon: 'none',
						title: '时间跨度不能超过90天'
					})
					return
				}
			}
			queryParam.value.endVerifyTime = e
		}
		type.value = ''
	}
	
	const query = () => {
		if (!queryParam.value.startVerifyTime) {
			uni.showToast({
				icon: 'none',
				title: '请选择开始时间'
			})
			return
		} else if (!queryParam.value.endVerifyTime) {
			uni.showToast({
				icon: 'none',
				title: '请选择结束时间'
			})
			return
		}
		let data = JSON.parse(JSON.stringify(queryParam.value))
		data.businessIdsStr = data.businessIds.join()
		delete data.businessIds
		toExport(exportApi(data))
	}
	
	const fillZero = (val) => {
		return val < 10 ? `0${val}` : val
	}
	
	// 订单导出格式：订单yyyyMMddHHmmss格式的时间+6位随机数
	const createFileName = () => {
		const now = new Date()
		const randomNum = ('000000' + Math.floor(Math.random() * 999999)).slice(-6)
		return `订单${now.getFullYear()}${fillZero(now.getMonth()+1)}${fillZero(now.getDate())}${fillZero(now.getHours())}${fillZero(now.getMinutes())}${fillZero(now.getSeconds())}${randomNum}.xlsx`
	}
	
	const toExport = async (url) => {
		const token = uni.getStorageSync('token')
		uni.downloadFile({
			url,
			header: {
				Authorization: token
			},
			success(res) {
				uni.shareFileMessage({
					filePath: res.tempFilePath,
					fileName: createFileName(),
					success() {
						onClose()
					},
					fail(err) {
						uni.showToast({
							icon: 'none',
							title: err && err.errMsg || '文件分享失败'
						})
					}
				})
			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: err && err.errMsg || '文件下载失败'
				})
			}
		})
	}
	
	defineExpose({
		showDialog
	})
</script>
<style scoped lang="scss">
	.item{
		width:102px;
		border:1px solid transparent;
		background-color: #f5f5f5;
	}
	.business-item{
		border:1px solid transparent;
		background-color: #f5f5f5;
	}
	.time-item{
		border:1px solid transparent;
		background-color: #f5f5f5;
	}
</style>